<template>
  <div class="user_information" style="position: relative">
    <el-dialog
      :title="dialogTitle"
      v-model="$headerNavStore.dialogVisible"
      width="40%"
    >
      <el-alert
        v-if="runSuccess"
        title="操作成功"
        type="success"
        center
        show-icon
        style="
          position: absolute;
          width: 50%;
          height: 25px;
          left: 50%;
          transform: translateX(-50%);
        "
        :closable="false"
      />
      <el-alert
        v-if="runFail"
        title="操作失败"
        type="error"
        center
        show-icon
        style="
          position: absolute;
          width: 50%;
          height: 25px;
          left: 50%;
          transform: translateX(-50%);
        "
        :closable="false"
      />
      <hr style="margin-bottom: 10px" color="#f0f0f0" />

      <div class="dialog_content" style="border: 1px solid #f0f0f0">
        <div class="toolbar">
          <div class="left_bar">
            <el-button
              class="add_traffic_btn"
              type="primary"
              :icon="Plus"
              circle
              @click="
                () => {
                  isShowAdd = true
                }
              "
            />
            <span class="add_traffic_intro">添加交管部门</span>
          </div>
          <div class="right_bar">
            <el-input
              v-model="keyword"
              style="width: 240px"
              placeholder="请输入用户名/用户类型"
              @input="searchUser()"
            />
            <el-button
              type="default"
              class="refresh-btn"
              @click="
                () => {
                  keyword = ''
                }
              "
              ><i class="iconfont icon-shuaxin"></i
            ></el-button>
            <el-tooltip content="导出Excel表格" placement="top">
              <el-button
                type="default"
                class="excel-btn"
                @click="exportExcel({ data: allData, name: '全体用户信息' })"
                ><i class="iconfont icon-Excel"></i
              ></el-button>
            </el-tooltip>
          </div>
        </div>

        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="type" label="用户类型" />
          <el-table-column prop="isOnline" label="登录状态" />
          <el-table-column label="操作">
            <template #default="scope">
              <el-button
                link
                type="success"
                size="small"
                @click.pervent="modifyUserInfor(scope.$index)"
              >
                修改
              </el-button>
              <el-button
                link
                type="danger"
                size="small"
                @click.pervent="deleteUserInfor(scope.$index)"
                >删除</el-button
              >
              <el-button
                link
                type="warning"
                size="small"
                @click.prevent="loginOutUser(scope.$index)"
                
                >下线</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <div class="modify_frame" v-if="isShowModify">
          用户名
          <span
            class="close_modify"
            @click="
              () => {
                isShowModify = false
              }
            "
            >X</span
          >
          <el-input
            v-model="modefiedUserName"
            style="width: 240px"
            placeholder="请输入修改后的用户名"
          />
          密码
          <el-input
            v-model="modefiedPassword"
            style="width: 240px"
            placeholder="请输入修改后的密码"
            @input="changePassword(modefiedPassword)"
          />
          <div class="password_tip" v-if="isShowPasswordTip">
            请输入6到11位英文或数字字符的密码
          </div>

          <el-button
            type="primary"
            style="width: 120px; margin: 15px auto 0"
            @click="submitModifiedInfor"
          >
            确认修改<el-icon class="el-icon--right">
              <Upload />
            </el-icon>
          </el-button>
        </div>

        <div class="modify_frame add_new_traffic" v-if="isShowAdd">
          用户名
          <span
            class="close_modify"
            @click="
              () => {
                isShowAdd = false
              }
            "
            >X</span
          >
          <el-input
            v-model="addedUserName"
            style="width: 240px"
            placeholder="请输入用户名"
          />
          密码
          <el-input
            v-model="addedPassword"
            style="width: 240px"
            placeholder="请输入密码"
            @input="changePassword(addedPassword)"
          />
          <div class="password_tip" v-if="isShowPasswordTip">
            请输入6到11位英文或数字字符的密码
          </div>
          <el-button
            type="primary"
            style="width: 120px; margin: 15px auto 0"
            @click="addTrafficUser"
          >
            确认添加<el-icon class="el-icon--right">
              <Upload />
            </el-icon>
          </el-button>
        </div>

        <el-pagination
          background
          layout="prev, pager, next"
          :total="listData.length"
          :page-size="6"
          @current-change="handleTableChange"
        >
        </el-pagination>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { axios } from '../../main.js'
import { Upload } from '@element-plus/icons-vue'
import { exportExcel } from './hooks/exportExcel.js'
import { useHeaderNavStore } from '@/stores/counter'
import { Plus } from '@element-plus/icons-vue'
let $headerNavStore = useHeaderNavStore()

// 弹窗名
const dialogTitle = ref('用户信息')
// 搜索值
const keyword = ref('')
// 当前表格页展示信息
const tableData = ref([])
// 来自后端的所有用户信息
const allData = ref([])
// 对后端所有的用户信息进行修改后的数据,用于页面渲染
const listData = ref([])
// 更改后的用户类型
const modefiedUserType = ref('')
// 更改后的用户名
const modefiedUserName = ref('')
// 更改后的密码
const modefiedPassword = ref('')
// 是否提示密码规范
const isShowPasswordTip = ref(false)
// 是否开启修改弹窗
const isShowModify = ref(false)
// 是否开启添加traffic弹窗
const isShowAdd = ref(false)
// 新增traffic用户的用户名
const addedUserName = ref('')
// 新增traffic用户的密码
const addedPassword = ref('')
//操作成功弹窗
const runSuccess = ref(false)
// 操作失败弹窗
const runFail = ref(false)
// 当前受操作用户的index值
let userIndex
// 当前页
let currentPage = 1
onMounted(() => {
  // 监听headerNavStore的dialogVisible变化
  watch(
    () => $headerNavStore.dialogVisible,
    (newVal) => {
      if (newVal) {
        // 刷新用户信息
        updataUsersInfor()
      }
    }
  )
})

watch(keyword, (newVal) => {
  // 设置表单目前展示数据
  if (!newVal) {
    updataUsersInfor()
  }
})
// ===========================更新用户信息===========================
async function updataUsersInfor() {
  allData.value = []
  // 获取普通用户信息
  const commonRes = await axios.get(`/api/user?type=common`)

  allData.value.unshift(commonRes.result)
  // 获取交管部门用户信息
  const trafficRes = await axios.get('/api/user?type=traffic')
  allData.value.unshift(trafficRes.result)
  //  获取管理员用户信息


  const adminRes = await axios.get('/api/user?type=admin')
  allData.value.unshift(adminRes.result)
  // 数组降至一维
  allData.value = allData.value.flat('Infinity')
  allData.value = allData.value.flat('Infinity')
  // 简单拷贝一份alldata数据
  listData.value = JSON.parse(JSON.stringify(allData.value))
  // 对listData数据进行修改，由于是拷贝过后的数据，此更改不会对allData数据产生任何影响
  listData.value.forEach((item) => {
    if (item.type == 'common') {
      item.type = '普通用户'
    } else if (item.type == 'traffic') {
      item.type = '交管部门'
    } else {
      item.type = '超级管理员'
    }

    if (item.isOnline) {
      item.isOnline = '在线'
    } else {
      item.isOnline = '离线'
    }
  })
  // 设置表单目前展示数据
  tableData.value = listData.value.slice((currentPage - 1) * 6, currentPage * 6)
}

// ===========================换页操作===========================
const handleTableChange = (curPage) => {
  //  获取当前页
  currentPage = curPage
  // 更新当前页展示信息
  tableData.value = listData.value.slice((currentPage - 1) * 6, currentPage * 6)
}
// ===========================修改用户信息===========================
function modifyUserInfor(index) {
  // 开启修改弹窗
  isShowModify.value = true
  // 指定受操作用户的index值
  userIndex = (currentPage - 1) * 6 + index
  // 初始化修改值
  modefiedUserType.value = allData.value[userIndex].type
  modefiedUserName.value = allData.value[userIndex].username
  modefiedPassword.value = allData.value[userIndex].password
}

// 判断输入的密码是否符合规范
function changePassword(password) {
  // 密码规范：6-11位数字或英文字符
  if (/^[A-Za-z0-9]{6,11}$/.test(password)) {
    isShowPasswordTip.value = false
  } else {
    isShowPasswordTip.value = true
  }
}
// ===========================提交修改后的用户信息===========================
async function submitModifiedInfor() {
  if (/^[A-Za-z0-9]{6,11}$/.test(modefiedPassword.value)) {
    const isModify = confirm('是否提交修改信息')
    if (isModify) {
      // 获取修改过后的用户信息
      const newUserInfor = {
        type: modefiedUserType.value,
        username: modefiedUserName.value,
        password: modefiedPassword.value,
        id: allData.value[userIndex].id,
      }
      // 修改
      const res = await axios.post('/api/change', newUserInfor)
      if (res.code == 200) {
        openSuccessTip()
        // 关闭修改弹窗
        isShowModify.value = false
        // 更新用户信息
        updataUsersInfor()
      } else {
        openfailTip()
      }
    }
  }
}
// ===========================删除用户信息===========================
async function deleteUserInfor(index) {
  const isDelete = confirm('是否删除此用户')
  if (isDelete) {
    // 指定受操作用户的index值
    userIndex = (currentPage - 1) * 6 + index
    // 获取删除对象
    let deleteUser = allData.value[userIndex]
    // 删除
    const res = await axios.post('/api/delete', {
      type: deleteUser.type,
      username: deleteUser.username,
    })
    if (res.code == 200) {
      openSuccessTip()
      // 更新用户信息
      updataUsersInfor()
    } else {
      openfailTip()
    }
  }
}
// ===========================用户下线===========================
async function loginOutUser(index) {
  // 指定受操作用户的index值
  userIndex = (currentPage - 1) * 6 + index
  // 获取下线对象
  let logoutUser = allData.value[userIndex]
  // 判断用户是否在线
  if (logoutUser.isOnline) {
    let isLogout = confirm('是否使该用户下线')
    if (isLogout) {
      // 下线
      const res = await axios.post('/api/logout', {
        "type": logoutUser.type,
        "username": logoutUser.username
      })
      if (res.code == 200) {
        openSuccessTip()
        // 更新用户信息
        updataUsersInfor()
      } else {
        openfailTip()
      }
    }
  }else{
    openfailTip()
  }

}

// ===========================添加traffic用户===========================
async function addTrafficUser() {
  if (/^[A-Za-z0-9]{6,11}$/.test(addedPassword.value)) {
    const trafficUser = {
      type: 'traffic',
      username: addedUserName.value,
      password: addedPassword.value,
    }
    const res = await axios.post('/api/register', trafficUser)
    if (res.code == 200) {
      //  关闭添加弹窗
      isShowAdd.value = false
      openSuccessTip()
      // 更新用户信息
      updataUsersInfor()
    } else {
      openfailTip()
    }
  }
}
// ===========================搜索功能 ===========================
function searchUser() {
  // 过滤出符合搜索条件的用户
  listData.value = listData.value.filter((item) => {
    // 可通过用户名以及用户类型进行搜索
    return (
      item.username.includes(keyword.value) ||
      item.type.startsWith(keyword.value)
    )
  })
  // 设置表单目前展示数据
  tableData.value = listData.value.slice((currentPage - 1) * 6, currentPage * 6)
}
// ===========================操作结果弹窗===========================
function openSuccessTip() {
  runSuccess.value = true
  setTimeout(() => {
    runSuccess.value = false
  }, 1500)
}

function openfailTip() {
  runFail.value = true
  setTimeout(() => {
    runFail.value = false
  }, 1500)
}
</script>

<style scoped lang="scss">
.toolbar {
  display: flex;
  justify-content: space-between;
  padding: 20px;

  .left_bar {
    .add_traffic_intro {
      margin-left: 10px;
      padding: 5px;
      border-radius: 5px;
      border: 1px solid #cdcdcd;
      opacity: 0;
      transition: 0.3s;
    }
  }

  .add_traffic_btn:hover + .add_traffic_intro {
    opacity: 1;
  }
}

.button_group {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  gap: 10px;
}

.modify_frame {
  position: absolute;
  left: 50%;
  top: 56%;
  transform: translateY(-50%) translateX(-50%);
  display: flex;
  width: 260px;
  padding: 10px;
  background-color: #fff;
  border-radius: 10px;
  flex-direction: column;
  gap: 10px;
  border: 1px solid #cdcdcd;
  z-index: 10;
  box-shadow: -3px -3px 20px #e4e5e7, 3px 3px 20px #ebebeb;
  font-size: x-small;
  text-align: left;
  color: grey;

  .password_tip {
    width: 100%;
    position: absolute;
    font-size: x-small;
    color: red;
    text-align: center;
    top: 136px;
    transform: translateX(-50%);
    left: 50%;
  }

  .close_modify {
    position: absolute;
    top: 8px;
    right: 10px;
    cursor: pointer;
  }
}
</style>
